﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Web.Security;
using Microhard.Permission.Interface;
using Microhard.Permission.Models;
using Microsoft.Practices.Unity;
using Microhard.Permission;
using Microhard.Core.DBUtility;
using Microhard.Core;

namespace Microhard.Permission_MembershipImpl
{
    public class RoleImpl : IRole
    {
        #region IRole Members

        public List<User> GetUsersByRole(string roleName)
        {
            string[] useName = Roles.GetUsersInRole(roleName);
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();

            List<User> userList = new List<User>();
            foreach (var name in useName)
            {
                User u = db.aspnet_Users.SingleOrDefault(n => n.UserName == name).ToModel();
                userList.Add(u);
            }
            return userList;
        }

        public Role GetByRoleName(string roleName)
        {
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            var result = db.aspnet_Roles.SingleOrDefault(r => r.RoleName == roleName);
            if (result != null)
                return result.ToModel();
            return null;
        }
        #endregion

        #region IRepository<Role> Members

        public ExecutedResult Add(Role model)
        {
            ExecutedResult rtn = new ExecutedResult();
            try
            {
                if (Roles.RoleExists(model.RoleName) == false)
                {
                    Roles.CreateRole(model.RoleName);
                    rtn.Scope.IsSysManage = true;
                }
            }
            catch (Exception ex)
            {
                rtn.ErrorMsg.Add("Role.Add", "添加用户失败，请联系系统管理员");
                Log.Error("Role.Add", ex);
            }

            return rtn;
        }

        public ExecutedResult Update(Role model)
        {
            throw new NotImplementedException();
        }

        public ExecutedResult Delete(List<Guid> ids)
        {
            ExecutedResult result = new ExecutedResult();
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            var deleteRoles = db.aspnet_Roles.Where(r => ids.Contains(r.RoleId));
            List<Guid> roleInGroupToDelList = new List<Guid>();

            foreach (var role in deleteRoles)
            {
                //用户是否使用了role
                int userIsUseRole = db.aspnet_UsersInRoles.Count(u => u.RoleId == role.RoleId);
                //权限是否使用了role
                int permissIsUseRole = db.MicroHard_Permissions.Count(p => p.OwnerID == role.RoleId && p.OwnerType == (int)OwnerIDType.Role);
                if (userIsUseRole > 0 || permissIsUseRole > 0)
                {
                    result.ErrorMsg.Add(role.RoleId.ToString(), "角色:" + role.RoleName + "正在使用中，无法删除");
                    continue;
                }
                if (result.ErrorMsg.Count == 0)
                {
                    bool rtn = Roles.DeleteRole(role.RoleName);
                    if (!rtn)
                    {
                        result.ErrorMsg.Add(role.RoleId.ToString(), "删除角色" + role.RoleName + "失败,请联系系统管理员");
                    }
                    else
                    { 
                       roleInGroupToDelList.Add(role.RoleId);
                    }
                }
            }
             //从组中删除已经被删除的角色
            if (roleInGroupToDelList.Count > 0)
            {
                var roleInGroupToDel = from d in db.MicroHard_EntitiesInGroups
                                       where roleInGroupToDelList.Contains(d.EntityID)
                                       && d.EntityType == (int)OwnerIDType.Role
                                       select d;
                db.MicroHard_EntitiesInGroups.DeleteAllOnSubmit(roleInGroupToDel);
                try
                {
                    db.SubmitChanges();
                }
                catch (Exception ex)
                {
                    result.ErrorMsg.Add("RoleImpl.Delete", ex.Message);
                }
            }

            return result;
        }

        public Role GetModelByID(Guid id)
        {
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            var result = db.aspnet_Roles.SingleOrDefault(r => r.RoleId == id);
            if (result != null)
                return result.ToModel();
            return null;
        }

        public List<Role> Query(Role Model, int pageIndex, int pageSize, out int totalCount)
        {
            throw new NotImplementedException();
        }

        public List<Role> Query(Role Model)
        {
            MicrohardOUGDBDataContext db = new MicrohardOUGDBDataContext();
            var roles = (from r in db.aspnet_Roles
                         select r).OrderBy(r => r.RoleName).ToList();
            return roles.Select(x => x.ToModel()).ToList();
        }

        public ExecutedResult Delete(Role models)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IRepository<Role> Members


        public Role GetModelByModel(Role model)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IRepository<Role> Members


        public ScopeResult scope
        {
            set;
            get;
        }

        #endregion
    }
}
